<!--  -->
<template>
  <div>
    <el-button type="primary" icon="el-icon-plus" style="margin:10px 0px;" @click="addTradeMark">添加</el-button>
    <el-table
      style="width: 100%"
      border
      :data="list"
    >
      <el-table-column
        prop="id"
        label="序号"
        width="100px"
        align="center"
      />
      <el-table-column
        prop="tmName"
        label="品牌名称"
        width="width"
      />
      <el-table-column
        prop="prop"
        label="品牌LOGO"
        width="width"
      >
        <!-- eslint-disable-next-line -->
        <template slot-scope="{row, $index}">
          <img :src="row.logoUrl" alt="" style="width:60px;height:60px">
        </template>
      </el-table-column>
      <el-table-column
        prop="prop"
        label="操作"
        width="width"
      >
        <!-- eslint-disable-next-line -->
        <template slot-scope="{row, $index}">
          <el-button type="warnning" icon="el-icon-edit" size="mini" @click="updateTradeMark(row)">修改</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteTradeMark(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top:20px; textAlign:center"
      :current-page="1"
      :page-sizes="[5, 10, 20]"
      :page-size="5"
      :page-count="8"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      prev-text="上一页"
      next-text="下一页"
      hide-on-single-page
      @size-change="handleSizeChange"
      @current-change="getPageList"
    />

    <el-dialog :title="tradeForm.id?'修改品牌':'添加品牌'" :visible.sync="dialogFormVisible">
      <el-form ref="ruleForm" style="width:80%" :model="tradeForm" :rules="rules">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input v-model="tradeForm.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" style="margin-left:10px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :show-file-list="false"
          >
            <img v-if="tradeForm.logoUrl" :src="tradeForm.logoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'TradeMaerk',
  data() {
    // 自定义校验规则
    var validateTmName = (rule, value, callback) => {
      if (value.length < 2 || value.length > 10) {
        callback(new Error('品牌名称2-10位'))
      } else {
        callback()
      }
    }
    return {
      page: 1,
      limit: 3,
      total: 0,
      list: [],
      dialogFormVisible: false,
      tradeForm: {
        tmName: '',
        logoUrl: ''
      },
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          // { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'change' }
          // 自定义校验规则
          { validator: validateTmName, trigger: 'change' }
        ],
        logoUrl: [
          { required: true, message: '请选择品牌的LOGO' }
        ]
      }
    }
  },
  mounted() {
    this.getPageList()
  },
  methods: {
    // 获取列表数据
    async getPageList(pager = 1) {
      this.page = pager
      const { page, limit } = this
      const result = await this.$API.trademark.reqTradeMark(page, limit)
      if (result.code === 200) {
        this.total = result.data.total
        this.list = result.data.records
      } else {
        console.log('error')
      }
    },
    handleSizeChange(limit) {
      this.limit = limit
      this.getPageList()
    },
    addTradeMark() {
      this.tradeForm = { tmName: '', logoUrl: '' }
      this.dialogFormVisible = true
    },
    updateTradeMark(tradeMark) {
      // 浅拷贝 避免修改内容后点击取消，造成显示异常
      this.tradeForm = { ...tradeMark }
      this.dialogFormVisible = true
    },
    // 图片上传成功
    handleAvatarSuccess(res, file) {
      // res、file为上传图片成功后，响应回来的数据 包括图片服务器真实地址
      this.tradeForm.logoUrl = res.data
    },
    // 图片上传之前
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    addOrUpdateTradeMark() {
      this.$refs.ruleForm.validate(async(success) => {
        if (success) {
          this.dialogFormVisible = false
          const result = await this.$API.trademark.reqAddOrUpdateTradeMark(this.tradeForm)
          if (result.code === 200) {
            // 弹出信息:添加品牌成功、修改品牌成功
            this.$message({
              type: 'success',
              message: this.tradeForm.id ? '修改品牌成功' : '添加品牌成功'
            })
            this.getPageList(this.tradeForm.id ? this.page : 1)
          }
        } else {
          return false
        }
      })
    },
    // 删除品牌
    deleteTradeMark(tradeMark) {
      this.$confirm(`确定要删除${tradeMark.tmName}吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const result = await this.$API.trademark.reqDeleteTradeMark(tradeMark.id)
        if (result.code === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getPageList(this.list.length > 1 ? this.page : this.page - 1)
        } else {
          this.$message({
            type: 'fail',
            message: '服务器异常，稍后再试!'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
